<?php
// 仅当会话尚未启动时调用 session_start()
include_once 'functions.php';
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
// 如果用户没有登录或角色不是 "reader"，则重定向到登录页面
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'reader') {
    header('Location: http://localhost/Library_management_system/index.php');
    exit();
}

// 数据库连接
try {
    $pdo = new PDO('mysql:host=localhost;dbname=library', 'root', '123456');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// 获取当前用户的 u_No
$u_No = $_SESSION['u_No'];

// 查询用户的借阅记录和状态描述
$sql = "
    SELECT l.Loan_Id, l.book_No, l.loan_date, l.Return_date, l.state_ID, 
           s.state_description, DATE_ADD(l.loan_date, INTERVAL 1 MONTH) AS due_date
    FROM Loan AS l
    INNER JOIN book AS b ON l.book_No = b.book_No
    INNER JOIN state AS s ON l.state_ID = s.state_ID
    WHERE l.u_No = :u_No
    ORDER BY l.loan_date DESC
";

$stmt = $pdo->prepare($sql);
$stmt->bindParam(':u_No', $u_No, PDO::PARAM_STR);
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 罚金计算函数调用
//function calculateFine($dueDate, $returnDate, $currentDate) {
 //   global $pdo;
    
 //   $stmt = $pdo->prepare("SELECT CalculateFine(:due_date, :return_date, :current_date) AS fine");
 //   $stmt->bindParam(':due_date', $dueDate);
 //  $stmt->bindParam(':return_date', $returnDate);
  //  $stmt->bindParam(':current_date', $currentDate);
  //  $stmt->execute();
  // $fine = $stmt->fetchColumn();
    
 //   return $fine;
//}

// 获取当前日期
$currentDate = date('Y-m-d');

// 归还图书操作
if (isset($_POST['return_book_id'])) {
    $book_id = $_POST['return_book_id'];

    // 1. 检查图书是否存在于用户借阅记录中
    $stmt = $pdo->prepare("SELECT Loan_Id FROM Loan WHERE u_No = :u_No AND book_No = :book_No AND state_ID = 'S001'");
    $stmt->bindParam(':u_No', $u_No);
    $stmt->bindParam(':book_No', $book_id);
    $stmt->execute();
    $loan_record = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($loan_record) {
        // 2. 更新 Loan 表中的归还日期和状态
        $stmt = $pdo->prepare("UPDATE Loan SET state_ID = 'S002', Return_date = :current_date WHERE Loan_Id = :loan_id");
        $stmt->bindParam(':current_date', $currentDate);
        $stmt->bindParam(':loan_id', $loan_record['Loan_Id']);
        $stmt->execute();

        // 3. 更新 book 表中的 Loan_Id 为 NULL（表示该书已经归还）
        $stmt = $pdo->prepare("UPDATE book SET Loan_Id = NULL WHERE book_No = :book_No");
        $stmt->bindParam(':book_No', $book_id);
        $stmt->execute();

        echo "图书已成功归还！";
    } else {
        echo "您没有借阅该图书或该图书尚未归还。";
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查看借阅记录</title>
</head>
<body>
    <h2>查看借阅记录</h2>
    
    <?php if (count($records) > 0): ?>
        <ul>
            <?php foreach ($records as $record): 
                $loanDate = $record['loan_date'];
                $returnDate = $record['Return_date'];
                $dueDate = $record['due_date'];
                $fine = 0.0;

                // 计算罚金
                if ($returnDate === null) {
                    if ($currentDate > $dueDate) {
                        // 图书未归还且逾期
                        $fine = calculateFine($dueDate, null, $currentDate);
                        $status = '超期未归还';
                    } else {
                        // 图书未归还且未逾期
                        $fine = 0.0;
                        $status = '已借阅';
                    }
                } else {
                    // 图书已经归还
                    $fine = calculateFine($dueDate, $returnDate, $currentDate);
                    if ($returnDate > $dueDate) {
                        $status = '超期归还';
                    } else {
                        $status = '正常归还';
                    }
                }
            ?>
                <li>
                    书籍ID: <?php echo htmlspecialchars($record['book_No']); ?>, 
                    借阅日期: <?php echo htmlspecialchars($loanDate); ?>, 
                    归还日期: <?php echo $returnDate ? htmlspecialchars($returnDate) : '未归还'; ?>, 
                    状态: <?php echo htmlspecialchars($record['state_description']); ?>, 
                    罚金: ￥<?php echo number_format($fine, 2); ?>
                    
                    <?php if ($returnDate === null): ?>
                        <!-- 提供归还按钮 -->
                        <form method="POST" action="">
                            <input type="hidden" name="return_book_id" value="<?php echo htmlspecialchars($record['book_No']); ?>">
                            <button type="submit">归还该图书</button>
                        </form>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php else: ?>
        <p>您没有借阅任何书籍。</p>
    <?php endif; ?>
</body>
</html>
